package com.sisyphus.mock.configs;

import com.google.gson.Gson;
import com.sisyphus.mock.data.model.BaseResponse;
import com.yanzhenjie.andserver.annotation.Resolver;
import com.yanzhenjie.andserver.error.HttpException;
import com.yanzhenjie.andserver.framework.ExceptionResolver;
import com.yanzhenjie.andserver.framework.body.JsonBody;
import com.yanzhenjie.andserver.http.HttpRequest;
import com.yanzhenjie.andserver.http.HttpResponse;

import com.yanzhenjie.andserver.http.StatusCode;

import androidx.annotation.NonNull;

@Resolver
public class GlobalExceptionResolver implements ExceptionResolver {

    @Override
    public void onResolve(@NonNull HttpRequest request, @NonNull HttpResponse response, @NonNull Throwable e) {
        e.printStackTrace();

        if (e instanceof HttpException) {
            HttpException exception = (HttpException) e;
            response.setStatus(exception.getStatusCode());
        } else {
            response.setStatus(StatusCode.SC_INTERNAL_SERVER_ERROR);
        }

        String body = new Gson().toJson(new BaseResponse<>(response.getStatus(), e.getMessage(), null));
        response.setBody(new JsonBody(body));
    }

}